﻿using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;

public class Server : MonoBehaviour{
    Socket serverSocket;
    Socket clientSocket;
    Thread clientThread;
    Thread t;
    // Use this for initialization
    void Start(){
        t = new Thread(new ThreadStart(OpenServer));
        t.Start();
    }
    void OnDestroy(){
		t.Abort();
        clientThread.Abort();
        serverSocket.Close();
	}

    void OpenServer(){
        IPAddress ipAdr = IPAddress.Parse("127.0.0.1");
        IPEndPoint ipEp = new IPEndPoint(ipAdr, 2234);
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        serverSocket.Bind(ipEp);
        serverSocket.Listen(10);

        while (true){
            try{
                clientSocket = serverSocket.Accept();
                Debug.Log("Accept");
                clientThread = new Thread(new ThreadStart(ReceiveData));
                clientThread.Start();

            }catch (System.Exception ex){
                print(ex);
                break;
            }
        }
    }
    void ReceiveData(){
        bool keepalive = true;
        Socket s = clientSocket;
        byte[] buffer = new byte[1024];

        IPEndPoint clientep = (IPEndPoint)s.RemoteEndPoint;
        string welcome = "IP为" + clientep.Address + "的客户端连接成功";
        byte[] data = new byte[1024];
        data = Encoding.UTF8.GetBytes(welcome);
        s.Send(data, data.Length, SocketFlags.None);
        
        while (keepalive){
            int bufLen = 0;
            try{
                bufLen = s.Available;
                s.Receive(buffer, 0, bufLen, SocketFlags.None);
                if (bufLen == 0)
                    continue;
            }catch (Exception ex){
                Debug.Log("Receive Error:" + ex.Message);
                return;
            }
            clientep = (IPEndPoint)s.RemoteEndPoint;
            string clientcommand = System.Text.Encoding.UTF8.GetString(buffer).Substring(0, bufLen);
            Debug.Log("服务端收到:" + clientcommand);
        }
    }
}